﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using System.Windows.Input;

namespace DataAnalyticsTools
{
    public static class GeneralConvertors
    {
        /// <summary>
        /// 转换为向量（浮点数组）
        /// </summary>
        /// <param name="embeddingString">字符串类型的浮点数组，兼容Embedding服务</param>
        /// <returns>浮点数</returns>
        public static float[] ConvertToFloatArray(string embeddingString)
        {
            if (string.IsNullOrEmpty(embeddingString))
                return null;

            embeddingString = embeddingString.Trim('[', ']'); // 去除方括号   
            embeddingString = embeddingString.Replace(" ", ""); // 去除空格
            embeddingString = embeddingString.Replace("\r\n", ""); // 去除换行符

            var arr = embeddingString.Split(',');
            float[] result = new float[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                result[i] = float.Parse(arr[i]);
            }
            return result;
        }

        /// <summary>
        /// 转换为向量（浮点数组）
        /// </summary>
        /// <param name="target">原始数据</param>
        /// <returns>浮点数组</returns>
        /// <exception cref="ArgumentException">不支持的数据格式</exception>
        public static float[] ConvertToFloatArray(object target)
        {

            if (target == null)
            {
                return [];
            }

            if (target is string embedding)
            {
                return ConvertToFloatArray(embedding);
            }

            if (target is ArrayList arr)
            {
                return [.. arr.ToArray().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is IEnumerable enumerable)
            {
                return [.. enumerable.Cast<object>().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is float[] arrFloat)
            {
                return arrFloat; // 如果已经是浮点数组，直接返回
            }

            if (target is double[] arrDouble)
            {
                return arrDouble.Select(x => (float)x).ToArray(); // 如果是双精度数组，转换为浮点数组
            }

            if(target is IDictionary<string, object> dict) // 兼容活字格的对象类型
            {
                return [.. dict.Values.Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is IList list)
            {
                return [.. list.Cast<object>().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is JsonArray jsonArray)
            {
                return [.. jsonArray.Select(x => (x is JsonValue jsonValue) ? (float)jsonValue : float.Parse(x.ToString()))]; // 如果是JsonArray类型，转换为浮点数组
            }

            return [];
        }

        /// <summary>
        /// 转换为二维向量（浮点数组的数组）
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <returns>浮点数组的数组</returns>
        /// <exception cref="ArgumentException">不支持的数据格式</exception>
        public static float[][] ConvertToFloatMatrix(object data)
        {

            if(data == null)
                return Array.Empty<float[]>();

            if (data is float[][] floatArray2D)
            {
                return floatArray2D;
            }
            else if (data is double[][] doubleArray2D)
            {
                return doubleArray2D.Select(row => row.Select(d => (float)d).ToArray()).ToArray();
            }
            else if (data is int[][] intArray2D)
            {
                return intArray2D.Select(row => row.Select(i => (float)i).ToArray()).ToArray();
            }
            else if (data is IEnumerable<object> objEnumerable2D)
            {
                var list = new List<float[]>();
                foreach (var row in objEnumerable2D)
                {
                    var floatRow = ConvertToFloatArray(row);
                    list.Add(floatRow.ToArray());
                }
                return list.ToArray();
            }
            else
            {
                throw new ArgumentException("输入数据类型不受支持");
            }
        }

        /// <summary>
        /// 转换为字符串数组
        /// </summary>
        /// <param name="target">原始数据</param>
        /// <returns>字符串数组</returns>
        /// <exception cref="ArgumentException">不支持的类型</exception>
        public static string[] ConvertToStringArray(object target)
        {
           if(target== null)
                return Array.Empty<string>();


            if (target is string str)
            {
                return str.Split(',');
            }
            if (target is string[] strArray)
            {
                return strArray;
            }
            if (target is ArrayList arr)
            {
                return [.. arr.ToArray().Select(x => x.ToString())];
            }
            if (target is IEnumerable enumerable)
            {
                return [.. enumerable.Cast<object>().Select(x => x.ToString())];
            }
            if (target is IList list)
            {
                return [.. list.Cast<object>().Select(x => x.ToString())];
            }
            if (target is JsonArray jsonArray)
            {
                return [.. jsonArray.Select(x => x.ToString())];
            }
            throw new ArgumentException("不支持的类型");
        }

        /// <summary>
        /// 转换为整数数组
        /// </summary>
        /// <param name="embeddingString">兼容ConvertToVector风格</param>
        /// <returns></returns>
        public static int[] ConvertToIntArray(string embeddingString) {
            if (string.IsNullOrEmpty(embeddingString))
                return null;

            embeddingString = embeddingString.Trim('[', ']'); // 去除方括号   
            embeddingString = embeddingString.Replace(" ", ""); // 去除空格
            embeddingString = embeddingString.Replace("\r\n", ""); // 去除换行符

            var arr = embeddingString.Split(',');
            int[] result = new int[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                result[i] = int.Parse(arr[i]);
            }
            return result;
        }

        /// <summary>
        /// 转换为整数数组
        /// </summary>
        /// <param name="target">原始数据</param>
        /// <returns>整数数组</returns>
        /// <exception cref="ArgumentException">不支持的格式</exception>
        public static int[] ConvertToIntArray(object target)
        {
            if (target == null)
                return Array.Empty<int>();
            if (target is int[] intArray)
            {
                return intArray;
            }
            if (target is string str)
            {
                return ConvertToIntArray(str);
            }
            if (target is ArrayList arr)
            {
                return [.. arr.ToArray().Select(x => (x is int) ? (int)x : int.Parse(x.ToString()))];
            }
            if (target is IEnumerable enumerable)
            {
                return [.. enumerable.Cast<object>().Select(x => (x is int) ? (int)x : int.Parse(x.ToString()))];
            }
            if (target is IList list)
            {
                return [.. list.Cast<object>().Select(x => (x is int) ? (int)x : int.Parse(x.ToString()))];
            }
            if (target is JsonArray jsonArray)
            {
                return [.. jsonArray.Select(x => (x is JsonValue jsonValue) ? (int)jsonValue : int.Parse(x.ToString()))];
            }
            throw new ArgumentException("不支持的类型");
        }
    }
}
